package proyecto.servlet;

import java.io.IOException;
import java.util.Collection;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import proyecto.excepcion.*;
import proyecto.negocio.*;
import proyecto.modelo.*;

@WebServlet("/CuotasServlet")
public class CuotasServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public CuotasServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.processRequest(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.processRequest(request, response);
	}

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String accion = request.getParameter("accion");
		HttpSession session = request.getSession();
		
		Usuario usuarioLogueado = (Usuario) session.getAttribute("USUARIO_ACTUAL");
		
		CuotaNegocio negocio= new CuotaNegocio();
		
		if(accion.equals("listarPendientesApagar")){			
			try {
				Collection<Cuota> lista = negocio.getCuotasPendientesDeUsuario(usuarioLogueado.getUsuario());
				request.setAttribute("cuotasPendientes", lista);
				RequestDispatcher rd = request.getRequestDispatcher("listCuotasPendientes.jsp");
				rd.forward(request, response);

			} catch (DAOExcepcion e) {
				System.out.println(e.getMessage());
				RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
				rd.forward(request, response);
			}
		}else if(accion.equals("pagarCuota")){
			try {
				int idCuota = Integer.parseInt(request.getParameter("id").toString());
				negocio.pagarCuota(idCuota);
				
				RequestDispatcher rd = request.getRequestDispatcher("CuotasServlet?accion=listarPendientesApagar");
				rd.forward(request, response);

			} catch (DAOExcepcion e) {
				System.out.println(e.getMessage());
				RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
				rd.forward(request, response);
			}
		}else if(accion.equals("listarMorosos")){
			try {
				int idCuota = Integer.parseInt(request.getParameter("id").toString());
				negocio.pagarCuota(idCuota);
				
				RequestDispatcher rd = request.getRequestDispatcher("ok.jsp");
				rd.forward(request, response);

			} catch (DAOExcepcion e) {
				System.out.println(e.getMessage());
				RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
				rd.forward(request, response);
			}
		}
	}	

}
